package cn.lliiooll.launcher.update;

import cn.lliiooll.launcher.log.LogOut;
import cn.lliiooll.launcher.window.Window;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Zip {
	
	public static int size;

	public static void unZipFile(File file,String path) {
		Window.ujpb.setValue(0);
		try {
			@SuppressWarnings("resource")
			ZipFile zip = new ZipFile(file, Charset.forName("GBK"));
			//String name = zip.getName().substring(zip.getName().lastIndexOf('\\')+1, zip.getName().lastIndexOf('.'));
			File filepath = new File(path);
			if(!(filepath.exists())) {
				filepath.mkdirs();
			}
			LogOut.info("开始解压");
			Window.ujpb.setString("开始解压");
			Window.ujpb.setIndeterminate(true);
			for(Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
				ZipEntry entry = entries.nextElement();
				String zipEntryName = entry.getName();
				InputStream is = zip.getInputStream(entry);
				String outPath = (path +"/"+ zipEntryName).replaceAll("\\*", "/");
				File file1 = new File(outPath.substring(0, outPath.lastIndexOf('/')));
				if(!(file1.exists())) {
					file1.mkdirs();
				}
				if(new File(outPath).isDirectory()) {
					continue;
				}
				FileOutputStream fos = new FileOutputStream(outPath);
				byte[] b = new byte[1024];
				int i;
				//File f = new File(path);
				//int sizebak = size;
				//getFile(f);
				size++;
				//Window.ujpb.setValue((int) (size/1024));
				Window.ujpb.setString("已解压" + size + "/" + zip.size() + "个文件");
				while((i = is.read(b)) > 0) {
					fos.write(b,0,i);
				}
				is.close();
				fos.close();
			}
			if(size < zip.size()) {
				size = zip.size();
			}
			LogOut.info("解压完成");
			Window.ujpb.setString("解压完成");
			FileSet.update(".minecraft", "tmp\\.minecraft");
			//Window.uw.dispose();
			//Window.updateCompeleteWindow();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	
    public static void getFile(File f){
        if(f!=null){
            if(f.isDirectory()){
                File[] fileArray=f.listFiles();
                if(fileArray!=null){
                    for (int i = 0; i < fileArray.length; i++) {
                        //递归调用
                        getFile(fileArray[i]);
                    }
                }
            }
            else{
                size++;
            }
        }
    }
}
